<?php

namespace App\Controller\Wap;

use App\Entity\Orders;
use App\Model\BannersModel;
use App\Model\MoneyExModel;
use App\Model\OrdersModel;
use App\Model\ShopGoodsModel;
use App\Model\UserLikesProductModel;
use App\Setting\BannersSetting;
use App\Base\BaseConfig;
use App\Base\BaseController4User;
use App\Model\LazyCommon\CCM;
use App\Model\LazyCommon\PlatConfigModel;
use App\Model\LazyCommon\RulesModel;
use Model\UserBundle\Entity\User;
use App\Model\LazyCommon\UserLoginLogModel;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteExModel;
use App\Model\LazyCommon\WechatModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/wap")
 */
class IndexController extends BaseController4User
{

    private function initData($session)
    {
        $request = Request::createFromGlobals();
        //获取用户信息
        $sessionOpenid = $session->get("openid");
        if (!$sessionOpenid) {
            $WechatModel = new WechatModel($this->getDoctrine());
            if(!$code = $this->getParamRequired("code")){
                $WechatModel->getWeChatCode($request->getUri(),1);
                die;
            }
            $WechatModel->getAccessToken4UserInfo($code);
            $session->set("openid",$WechatModel->Openid);
            $userInfo = $WechatModel->getWeChatUserInfo();
            $UserModel = new UserModel($this->getDoctrine());
            $user = $UserModel->getByWeChetId($userInfo->openid);
            $user->setNickName($userInfo->nickname)
                ->setHeadPic($userInfo->headimgurl)
//                ->setOpenid($userInfo->openid)
            ;
            $this->myEm()->persist($user);
            $this->myEm()->flush();
            $Model = new UserModel($this->getDoctrine());
            foreach ($Model->createSessionData($user) as $key => $value) {
                $session->set($key,$value);
            }

        }

//        else{
            //如果发现没有绑定手机号先绑定一下
        $phone = $session->get("phone");
        if (!$phone) {
            //跳转到绑定注册页面
            header("location:".$this->generateUrl("UserAppBindPhone"));
            die();
        }
//        }

        $isLogin = $this->getSessionData("isLogin") ;
        if (!$isLogin || $isLogin < time() - 24 * 3600) {
            $isLogin = time();
            $Model = new UserModel($this->getDoctrine());
            $uid = $this->isUser();
            if (!$uid) {
                $openid = $this->getOpenid();
                if (!$openid) {
                    die("<h1>请从公众号进入商城</h1>");
                }

                $user = $Model->getByWeChetId($openid);
            }else{
                $user = $Model->getUserById($uid);
            }
            $user->setLastLoginTime(time());
            $this->myEm()->persist($user);
            $this->myEm()->flush();

            $this->setSessionData($Model->createSessionData($user));
            //这里需要模拟登陆走一下
            $userLoginLogModel = new UserLoginLogModel($this->getDoctrine());
            $loginInfo = $userLoginLogModel->createLoginLogInfo($request);
            $loginInfo["userAccount"] = $user->getAccount();
            $loginInfo["passwordError"] = 0;
            $userLoginLogModel->addLoginLog($loginInfo);
            $this->setSessionData(array("isLogin"    => $isLogin));
        }

        return $this->data;
    }


    /**
     * @route("/index",name="UserAppIndex")
     */
    public function UserAppIndex(Request $request)
    {
//        $data = $this->initData($this->mySession());
        $data["error"]  = "";
        $data["redirect"] = "";
        $data["delay"] = "0";
        return $this->render("App/Wap/index_intro.php.twig",$data);
    }

    /**
     * @route("/home/index",name="UserAppHomeIndex")
     */
    public function UserAppHomeIndex(Request $request)
    {
        $data = $this->initData($this->mySession());
        $data["curTab"] = 1;

        //banner
        $BannersModel = new BannersModel($this->getDoctrine());
        $param = array();//$param[conditions][table][field][eq|gt|lt...]=value
        $BannerList = $BannersModel->getAdminLists($param,0,9999999);
        $data["banner"] = $BannerList["data"];

        //视频
        $PlatConfigModel = new PlatConfigModel($this->getDoctrine());
        $pc = $PlatConfigModel->get(7);

        $data["pc"] = $pc;

        //products
        $goods = $this->getAllGoodsList();
        $data["goods"] = $goods;
        $data["goodsJson"] = json_encode($goods);


        return $this->render("App/Wap/index.php.twig",$data);
    }

    /**
     * @route("/home/cart",name="UserAppHomeCart")
     */
    public function UserAppHomeCart()
    {
        $uid = $this->needToBeUser();
        $data = $this->initData($this->mySession());
        $data["curTab"] = 2;

        //宝贝收藏
        $UserLikesProductModel = new UserLikesProductModel($this->getDoctrine());
        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        $UserLikesProduct = $UserLikesProductModel->get4User($uid,0,100);
        $likes = array();
        foreach ($UserLikesProduct as $row) {
            $prodId = $row->getWhat();
            $prod = $ShopGoodsModel->getById($prodId);
            if (!$prod) {
                continue;
            }
            $likes[] = $this->toArray($prod);
        }
        $data["likes"] = $likes;

        //购买记录
        $Model = new OrdersModel($this->getDoctrine());
        $orders = $Model->getUserOrders($uid);
        $allOrders = $orders["s3"];//这里需要换成finished  s3
        $allOrders = $orders["all"];//这里需要换成finished  s3

        $data["buy"] = $allOrders;
        $data["status"] = BaseConfig::__ORDER_STATUS_NAME__;

        return $this->render("App/Wap/cart.php.twig",$data);
    }

    /**
     * @route("/home/share",name="UserAppHomeShare")
     */
    public function UserAppHomeShare(Request $request)
    {
        $uid = $this->needToBeUser();
        $Model = new UserModel($this->getDoctrine());
        $Entity = $Model->getUserById($uid);
        if ($Entity->getGroups() == 3) {
            $this->setError("购买任意产品就能开启分享模块");
            return $this->UserAppHomeIndex($request);
        }

        $data = $this->initData($this->mySession());

        //获取用户积分
        $MoneyExModel = new MoneyExModel($this->getDoctrine());
        $data["money"] = $MoneyExModel->getUserMoney4Web($uid);

        //获取用户阶段性积分
        $day = $MoneyExModel->getUserMoneyInTerm($uid,$this->getDayStart(),$this->getDayEnd());
        $month = $MoneyExModel->getUserMoneyInTerm($uid,$this->getMonthStart(),$this->getMonthEnd());

        $data["day"] = $day;
        $data["month"] = $month;

        //获取固定电话
        $RulesModel = new RulesModel($this->getDoctrine());
        $Rule = $RulesModel->getByK("service_tel");

        $data["tel"] = $Rule->getV();
        $data["curTab"] = 3;

        //获取用户信息并根据用户等级提示用户是否可以查看区域销量
        $Model = new UserModel($this->getDoctrine());
        $user = $Model->getUserById($uid);
        $data["user"] = $user;
        $data["isAgentArea"] = 0;
        if ($user->getGroups() > 6) {
            //用户等级属于区域代理
            $data["isAgentArea"] = 1;
        }
//        $data["isAgentArea"] = 1;



        return $this->render("App/Wap/share.php.twig",$data);
    }

    /**
     * @route("/home/user",name="UserAppHomeUser")
     */
    public function UserAppHomeUser()
    {
        $uid = $this->needToBeUser();
        $data = $this->initData($this->mySession());

        //获取用户信息
        $UserModel = new UserModel($this->getDoctrine());
        $user = $UserModel->getUserById($uid);
        $data["user"] = $UserModel->getBaseInfo($user);

        //获取推荐人信息
        $UserInviteExModel = new UserInviteExModel($this->getDoctrine());
        $parents = $UserInviteExModel->getUserParentsIdArray($uid);
        if (!$parents) {
            //没有推荐人？？？？！！！！
            $parent= new User();
            $parent->setGroups(3);
            $parent->setNickName("");
        }else{
            $parent = $UserModel->getUserById($parents[0]);
        }
        $data["parent"] = $UserModel->getBaseInfo($parent);

        //获取用户积分
        $MoneyExModel = new MoneyExModel($this->getDoctrine());
        $data["money"] = $MoneyExModel->getUserMoney4Web($uid);

        $data["curTab"] = 4;
        $BannersModel = new BannersModel($this->getDoctrine());
        $param = array();
        $BannerList = $BannersModel->getAdminLists($param,0,9999999);
        $data["banner"] = $BannerList["data"];
        return $this->render("App/Wap/user.php.twig",$data);
    }


    private function getAllGoodsList()
    {
        $ShopGoodsModel = new ShopGoodsModel($this->getDoctrine());
        $param["conditions"]["ShopGoods"]["status"]["eq"] = 1;
        $goodsList = $ShopGoodsModel->getAdminLists($param,0,9999);
        $goods = array();
        foreach ($goodsList["data"] as $one ) {
            $goods[] = array(
                "id"    => $one["ShopGoods_"."id"],
                "name"    => $one["ShopGoods_"."name"],
                "price"    => $one["ShopGoods_"."price"],
                "priceno"    => $one["ShopGoods_"."priceno"],
                "pic"    => $one["ShopGoods_"."pic"],
                "cover"    => $one["ShopGoods_"."cover"],
                "sale"    => $one["ShopGoods_"."sale"],
            );
        }
        return $goods;
    }





    /**
     * @route("/home/data/json",name="UserAppHomeDataJson")
     */
    public function UserAppHomeDataJson()
    {
        $uid = $this->needToBeUser();

        //1.获取各个订单分组的数据
        $OrderModel = new OrdersModel($this->getDoctrine());
        $data = $OrderModel->getUserOrdersNum($uid);

        //2.获取下级用户订单分组的数据
        $data["sons"] = $OrderModel->getUserSonOrdersNum($uid);
        return $this->json_out(1,"数据获取成功",$data);
    }
}
